﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Primitives;
using ST.Common.Util.Model;
using ST.Common.Util.Security;
using System.Text.RegularExpressions;

namespace ST.Common.Util.Mvc
{
	/// <summary>
	/// 具体业务的一些扩展方法
	/// </summary>
	public partial class BaseController
	{
		/// <summary>
		/// 微信Referer头部正则
		/// </summary>
		private static Regex WX_REFERER_REG = new Regex("https://servicewechat.com/([a-zA-Z0-9]+)/([a-zA-Z0-9\\.]+)/page-frame.html");

		///// <summary>
		///// 获取请求的微信formId
		///// </summary>
		///// <returns></returns>
		//protected virtual string GetWXFormID()
		//{
		//	StringValues _wxfid = Request.Headers["formid"];
		//	if (_wxfid.Count > 0)
		//	{
		//		return _wxfid[0];
		//	}
		//	return string.Empty;
		//}

		/// <summary>
		/// 获取当前请求的小程序AppID
		/// </summary>
		/// <returns></returns>
		protected virtual string GetRequestAppID()
		{
			string hdrReferer = Request.Headers["Referer"];
			string hdrAppID = Request.Headers["appid"];
			if (logger.IsEnabled(LogLevel.Debug))
			{
				logger.LogDebug($"获取到的Referer：{hdrReferer},appid:{hdrAppID}");
			}
			if (!string.IsNullOrEmpty(hdrAppID))
			{
				return hdrAppID;
			}
			if (!string.IsNullOrEmpty(hdrReferer))
			{
				Match m = WX_REFERER_REG.Match(hdrReferer);
				if (m.Success)
				{
					if (logger.IsEnabled(LogLevel.Debug))
					{
						logger.LogDebug($"通过Referer获取到的请求小程序ID为：{m.Groups[1].Value}，小程序版本号为：{m.Groups[2].Value}");
					}
					return m.Groups[1].Value;
				}
			}

			return string.Empty;
		}

		/// <summary>
		/// 获取当前请求的公众号AppID
		/// </summary>
		/// <returns></returns>
		protected virtual string GetRequestMPAppID()
		{
			string hdrAppID = Request.Headers["mpappid"];
			if (logger.IsEnabled(LogLevel.Debug))
			{
				logger.LogDebug($"获取到的mpappid:{hdrAppID}");
			}
			if (!string.IsNullOrEmpty(hdrAppID))
			{
				return hdrAppID;
			}
			return string.Empty;
		}

		///// <summary>
		///// 获取原始的AppID（比如公众号点击过来或其他小程序点击过来），如果直接通过小程序来的，则返回小程序AppID
		///// </summary>
		///// <returns></returns>
		//protected virtual string GetOriginalAppID()
		//{
		//	string originalAppID = string.Empty;
		//	var _appid = Request.Headers["appid"];
		//	if (_appid.Count > 0)
		//	{
		//		originalAppID = _appid[0];
		//	}
		//	if (string.IsNullOrEmpty(originalAppID))
		//	{
		//		originalAppID = GetRequestAppID();
		//	}
		//	return originalAppID;
		//}

		/// <summary>
		/// 根据会话信息生成客户端保存的会话信息
		/// </summary>
		/// <param name="sessionCurrent"></param>
		/// <returns></returns>
		protected virtual IActionResult GenSessionResult(UserSession sessionCurrent)
		{
			string authSessionBase64Str = EncryptHelper.AESEncrypt(sessionCurrent, sessionCurrent.UserCode, sessionCurrent.Timestamp);
			JsonResultBase respRet = new JsonResultBase(new
			{
				skey = authSessionBase64Str,
				ucode = sessionCurrent.UserCode,
				openid = sessionCurrent.OpenID,
				relatedid = sessionCurrent.RelatedOpenID,
				subscribe = sessionCurrent.Subscribe,
				state = sessionCurrent.State,
				roles = sessionCurrent.Roles,//角色ID列表，格式为",roleid1,"
				name = sessionCurrent.UserName,
				avatar = sessionCurrent.Avatar,
				lastdate = sessionCurrent.LastLoginDate,
				lastip = sessionCurrent.LastLoginIP,
				userid = sessionCurrent.UserID,
				usertype = sessionCurrent.UserType,
				orgpartnerid = sessionCurrent.OrgPartnerID
			});
			return respRet;
		}
	}
}
